<!-- 用户列表组件 -->
<template>
    <div class="users">
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 显示查询内容区域 -->

        <el-card class="box-card">
            <!-- 功能区域 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <!-- input双向绑定queryinfo查询数据，后面可以直接用queryinfo查询数据 -->
                    <el-input placeholder="请输入搜索内容" class="input-with-select" v-model="queryinfo.query" clearable
                        @clear="getUserData">
                        <el-button slot="append" icon="el-icon-search" @click="getUserData"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="6">
                    <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>

            <!-- 添加用户对话框 -->
            <el-dialog title="添加用户" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
                <span>
                    <el-form :model="addUser" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                        <el-form-item label="用户名" prop="username">
                            <el-input v-model="addUser.username"></el-input>
                        </el-form-item>
                        <el-form-item label="密码" prop="password">
                            <el-input v-model="addUser.password" type="password"></el-input>
                        </el-form-item>
                        <el-form-item label="email" prop="email">
                            <el-input v-model="addUser.email"></el-input>
                        </el-form-item>
                        <el-form-item label="手机号" prop="mobile">
                            <el-input v-model="addUser.mobile"></el-input>
                        </el-form-item>
                    </el-form>
                </span>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitAddUser">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 修改用户信息对话框 -->
            <el-dialog title="修改用户" :visible.sync="modifydialog" width="30%" :before-close="handleClose">
                <span>
                    <el-form :model="addUser" ref="modifyruleForm" label-width="100px" class="demo-ruleForm">
                        <el-form-item label="用户名">
                            <el-input v-model="modifyUser.username" :disabled="true"></el-input>
                        </el-form-item>
                        <el-form-item label="email">
                            <el-input v-model="modifyUser.email"></el-input>
                        </el-form-item>
                        <el-form-item label="手机号">
                            <el-input v-model="modifyUser.mobile"></el-input>
                        </el-form-item>
                    </el-form>
                </span>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="modifydialog = false">取 消</el-button>
                    <el-button type="primary" @click="submitModifyUserInfo">确 定</el-button>
                </span>
            </el-dialog>


            <!-- 删除用户信息对话框 -->
            <el-dialog title="修改用户" :visible.sync="deletedialog" width="30%" :before-close="handleClose">
                <span>
                    真的要删除吗？
                </span>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="deleteUserInfo">确定删除</el-button>
                    <el-button type="primary" @click="deletedialog = false">我再想想</el-button>
                </span>
            </el-dialog>

            <!-- 分配用户角色对话框 -->
            <el-dialog title="提示" :visible.sync="setUserCharaterVisiable" width="30%" :before-close="handleClose">
                <div>
                    <p>用户名：{{userInfo.username}}</p>
                    <p>身份：{{userInfo.rolename}}</p>
                        <el-select v-model="selectRoleDescId" placeholder="请选择">
                            <el-option v-for="item in userDesc" :key="item.id" :label="item.roleDesc"
                                :value="item.id">
                            </el-option>
                        </el-select>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="setUserCharaterVisiable = false">取 消</el-button>
                    <el-button type="primary" @click="submitSetUserCharater">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 显示用户区域 -->
            <el-table :data="userList" height="250" border style="width: 100%" stripe>
                <el-table-column type="index" label="#">
                </el-table-column>
                <el-table-column prop="username" label="用户名">
                </el-table-column>
                <el-table-column prop="email" label="邮箱">
                </el-table-column>
                <el-table-column prop="mobile" label="电话">
                </el-table-column>
                <el-table-column prop="role_name" label="身份">
                </el-table-column>
                <el-table-column prop="mg_state" label="状态">
                    <!-- 开关 -->
                    <!-- 使用具名插槽渲染状态列 -->
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change="mgStateChange(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="250">
                    <!-- 因为对用户条目的操作需要通过id标识，所以需要使用作用域插槽 -->
                    <template slot-scope="scope">
                        <!-- 修改用户信息 -->
                        <el-button type="primary" icon="el-icon-edit" @click="modifyUserInfo(scope.row)"></el-button>
                        <!-- 删除用户信息 -->
                        <el-button type="danger" icon="el-icon-delete" @click="showDeleteUserInfo(scope.row)">
                        </el-button>
                        <!-- 分配用户角色 -->
                        <el-tooltip content="分配用户角色" placement="top">
                            <el-button type="warning" icon="el-icon-s-tools" @click="setUserCharater(scope.row)">
                            </el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页功能区域 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="queryinfo.pagenum" :page-sizes="[2,5,7,10]" :page-size="queryinfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-card>
    </div>
</template>

<script>
    export default {
        created() {
            //打开页面显示发起请求
            this.getUserData()
        },
        data() {
            //邮箱验证
            var checkEmail = (rule, value, callback) => {
                const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
                if (mailReg.test(value)) {
                    callback()
                } else {
                    callback(new Error('请输入正确的邮箱格式'))
                }
            }

            return {
                queryinfo: {
                    //查询参数
                    // query是空是查询所有数据，query不为空时返回username符合条件的数据
                    query: '',
                    //当前页码
                    pagenum: 1,
                    //每页显示条数
                    pagesize: 2
                },
                userList: [],
                total: 10,
                // 添加用户对话框的显示与隐藏
                dialogVisible: false,
                // 修改用户对话框的显示与隐藏
                modifydialog: false,
                // 删除信息确认对话框
                deletedialog: false,
                //对话框表单验证规则
                rules: {
                    username: [{
                            require: true,
                            message: "用户名不能为空",
                            tirgger: "blur"
                        },
                        {
                            min: 3,
                            max: 10,
                            message: "用户名长度必须在3到10之间",
                            tirgger: "blur"
                        }
                    ],
                    password: [{
                            require: true,
                            message: "密码不能为空",
                            tirgger: "blur"
                        },
                        {
                            min: 6,
                            max: 18,
                            tirgger: 'blur',
                            message: "密码长度必须在6到18之间"
                        }
                    ],
                    email: [{
                        validator: checkEmail,
                        trigger: 'blur'
                    }],
                    mobile: [{
                        min: 11,
                        max: 11,
                        tirgger: 'blur',
                        message: "密码长度必须是11位"
                    }]
                },
                //添加用户数据
                addUser: {
                    username: '',
                    password: '',
                    email: '',
                    mobile: ''
                },
                modifyUser: {
                    id: null,
                    username: '',
                    email: '',
                    mobile: ''
                },
                //要删除的用户id
                delID: null,
                //是否显示分配用户角色对话框
                setUserCharaterVisiable: false,
                //要分配权限的用户信息
                userInfo: {
                    username: '',
                    rolename: ''
                },
                //其他用户描述
                userDesc:[],
                //选中的描述
                selectRoleDescId:'',
                //选中的需要修改描述的用户
                selectRoleId:''
            }
        },
        methods: {
            //获取用户信息
            async getUserData() {
                const {
                    data: res
                } = await this.$http.get('/users', {
                    params: this.queryinfo
                })
                // console.log(res)
                if (res.meta.status !== 200) {
                    return this.$message.error('获取用户列表失败')
                }
                this.userList = res.data.users
                this.total = res.data.total
            },
            //修改页面显示条目时重新发起请求
            handleSizeChange(size) {
                // 该函数只传递唯一参数：当前页面显示条目数
                // 改变页面显示最大条目数时，将该条目数传递给queryinfo.pagesize并重新发起请求
                this.queryinfo.pagesize = size
                this.getUserData()
            },
            //分页 修改页数重新发起请求
            handleCurrentChange(current) {
                // 该函数只传递唯一参数：当前页数
                // 改变页数时，将页数信息传递给queryinfo.pagenum并重新发起请求
                this.queryinfo.pagenum = current
                this.getUserData()
            },
            //修改用户状态
            async mgStateChange(ms) {
                const {
                    data: res
                } = await this.$http.put(`users/${ms.id}/state/${ms.mg_state}`)
                console.log(res)
                if (res.meta.status !== 200) {
                    ms.mg_state = !ms.mg_state
                    return this.$message.error('修改用户状态失败')
                }
                this.$message.success(res.meta.msg)
            },
            //开启关闭对话框
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {});
            },
            //提交添加用户信息
            submitAddUser() {
                this.$refs['ruleForm'].validate(async (valid) => {
                    if (valid) {
                        this.dialogVisible = false
                        const {
                            data: res
                        } = await this.$http.post('users', this.addUser)
                        if (res.meta.status !== 201) {
                            console.log(res)
                            return this.$message.error('创建用户失败')
                        }
                        this.$message.success('用户创建成功')
                        this.getUserData()
                    }
                })

            },
            //显示修改用户信息对话框
            modifyUserInfo(msg) {
                this.modifydialog = true
                console.log(msg);
                this.modifyUser.username = msg.username
                this.modifyUser.id = msg.id
                this.modifyUser.email = msg.email
                this.modifyUser.mobile = msg.mobile
            },
            //提交修改用户信息
            async submitModifyUserInfo() {
                const {
                    data: res
                } = await this.$http.put(`users/${this.modifyUser.id}`, this.modifyUser)
                if (res.meta.status !== 200) {
                    return this.$message.error('修改用户信息失败')
                }
                this.$message.success('修改用户信息成功')
                this.modifydialog = false
                this.getUserData()
            },
            //显示删除用户信息对话框
            showDeleteUserInfo(msg) {
                this.deletedialog = true
                this.delID = msg.id
            },
            //提交删除用户信息
            async deleteUserInfo() {
                const {
                    data: res
                } = await this.$http.delete(`users/${this.delID}`)
                if (res.meta.status !== 200) {
                    return this.$message.error('删除用户信息失败')
                }
                this.$message.success('删除用户信息成功')
                this.deletedialog = false
                this.getUserData()
            },
            //分配用户角色
            async setUserCharater(user) {
                this.userInfo.username = user.username
                this.userInfo.rolename = user.role_name
                this.setUserCharaterVisiable = true

                const {data:res} = await this.$http.get('roles')
                this.userDesc = res.data
                this.selectRoleId = user.id
            },
            //提交分配用户角色信息
            async submitSetUserCharater(){
                const {data:res} = await this.$http.put(`users/${this.selectRoleId}/role`,{rid:this.selectRoleDescId})
                if(res.meta.status!==200) {
                    return this.$message.error('修改角色描述失败！')
                }
                this.$message.success('修改用户描述成功')
                this.getUserData()
                this.setUserCharaterVisiable = false
            }
        }
    }
</script>
<style scoped>
    /* @import url(); 引入css类 */
    p {
        font-size: 16px;
        line-height: 25px;
    }
</style>